import { green, yellow } from "chalk";
import consola from "consola";
import { copySync } from "fs-extra";
import { prompt } from "inquirer";
import { join, resolve } from "path";

import packageJson from "../package.json";

const CWD = process.cwd();
const TEMPLATE_DIR = join(__dirname, "../templates");

const PROMPTS = [
  {
    name: "name",
    message: "Please choices tools",
    type: "list",
    choices: ["Webpack", "Vite", "UniApp", "Next"],
  },
];

const FRAMES = [
  {
    name: "name",
    message: "Please choices framework",
    type: "list",
    choices: ["React", "Vue"],
  },
];

class Generator {
  name: string;
  projectName: string;
  promptsName: string;
  framesName: string;
  libraryName: string;
  toolsName: string;
  frameworkName: string;
  injectScript: string;
  outputDir: string;
  NextVersion: string;
  constructor(name: string) {
    this.name = "";
    this.promptsName = "";
    this.framesName = "";
    this.toolsName = "";
    this.frameworkName = "";
    this.libraryName = "";
    this.injectScript = "";
    this.NextVersion = packageJson.version;
    this.projectName = name;
    this.outputDir = join(CWD, name);
  }
  async run() {
    await this.prompting();
    await this.frameing();
    await this.writing();
    await this.end();
  }
  async prompting() {
    const { name } = await prompt(PROMPTS);
    this.toolsName = name.toLowerCase();
    this.promptsName = name;
  }
  async frameing() {
    if (["UniApp", "Next"].includes(this.promptsName)) {
      this.framesName = "";
    } else {
      const { name } = await prompt(FRAMES);
      this.frameworkName = name.toLowerCase();
      this.framesName = name;
    }
  }
  async writing() {
    if (this.promptsName) {
      consola.info(`Creating project in ${green(this.outputDir)}\n`);
      const templatePath = join(resolve(TEMPLATE_DIR, this.promptsName.toLowerCase(), this.framesName.toLowerCase())).replace(
        /\\/g,
        "/"
      );
      copySync(templatePath, this.outputDir);
    }
  }
  async end() {
    consola.success(`Successfully created ${yellow(this.projectName)}.`);
    consola.success(
      `Run ${yellow(
        `cd ${this.projectName} && npm install && npm run dev`
      )} to start development!`
    );
  }
}

export default Generator;
